package com.team5101.web.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
public class AliPayController {

    @RequestMapping("success")
    public String toSuccess(){
        return "success";
    }


    @Value("${NATAPPIP}")
    public String natAppIp;




    @RequestMapping("alipay")
    public void doPay(HttpServletRequest httpRequest,
                      HttpServletResponse httpResponse,String oid) throws ServletException, IOException {

        AlipayClient alipayClient =
                new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                        "2016101900725231",
                        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLCXuZFtjDvVtL7oX/Xe4hQh8InMVkZ6yAoxd/h3e7YNnSmcRTbp0xn0Ol3JHHaCGX7qkM4tKTBvG23S7P2PDtzu/4y4CFDG7sei3y6CUZSjsrdM+HpDBo46IyFDVaOQNcUT9NFCtJtEsrO+ZDbAcrq6pFH+8ynY9K+WpQb7wYwPL1bKZxa5Z9QGOJ63iQKRvKOFRNJJxET6z5UGlEc2+uUHsW6kgXJ6WPm9nPHeGiowRWnbwc+cC/4QBDe1NiKcrqDucbk4tRlMszFdc3yGrbB/BWNT+fjSgqthMWdkTP5b+XnZntBE4MQC8V9mdENaqZb/E9h2dEXniQFIVAXiRHAgMBAAECggEAW5BrLW62YnIZ5e+3n22knZKGDY3xESaVnEHL/9ifKW+nA+L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xLhQe/7Vaw0nWWP7H7faCcmZDSi3s5CM6hkMAl3khuoQhTOgTrw9NpWgatsA+AlxCvlaRjgzuLSLPm/ZkZzJyM=",
                        "json",
                        "UTF-8",
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiwl7mRbYw71bS+6F/13uIUIfCJzFZGesgKMXf4d3u2DZ0pnEU26dMZ9DpdyRx2ghl+6pDOLSkwbxtt0uz9jw7c7v+MuAhQxu7Hot8uglGUo7K3TPh6QwaOOiMhQ1WjkDXFE/TRQrSbRLKzvmQ2wHK6uqRR/vMp2PSvlqUG+8GMDy9WymcWuWfUBjiet4kCkbyjhUTSScRE+s+VBpRHNvrlB7FupIFyelj5vZzx3hoqMEVp28HPnAv+EAQ3tTYinK6g7nG5OLUZTLMxXXN8hq2wfwVjU/n40oKrYTFnZEz+W/l52Z7QRODEAvFfZnRDWqmW/xPYdnRF54kBSFQF4kRwIDAQAB",
                        "RSA2"); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(natAppIp+"/success");
        alipayRequest.setNotifyUrl(natAppIp+"/notifyUrl");//在公共参数中设置回跳和通知地址

        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":  \""+oid+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":80.0," +
                "    \"subject\":\"Iphone6 32G\"," +
                "    \"body\":\"Iphone6 32G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset="+"UTF-8");
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    @RequestMapping("notifyUrl")
    @ResponseBody
    public void notifyUrl(HttpServletRequest request ,HttpServletResponse response) throws AlipayApiException, IOException {

        Map<String, String[]> KMap = request.getParameterMap();
        Map<String, String> paramsMap = new HashMap<String,String>(); //将异步通知中收到的所有参数都存放到 map 中
        for (String s : KMap.keySet()) {
            //System.out.println("s"+s);
            //System.out.println("value"+KMap.get(s).toString());
            StringBuffer strBuffer = new StringBuffer();
            int len=KMap.get(s).length;
            for(int i=0;i<len-1;i++){
                strBuffer.append(KMap.get(s)[i]);
                strBuffer.append(",");
            }
            strBuffer.append(KMap.get(s)[len-1]);

            paramsMap.put(s,strBuffer.toString());
        }



        boolean signVerfied = AlipaySignature.rsaCheckV1(paramsMap,
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgO/rQgSZvR/afCbY6qADRmx1VS5B9f1h41F6dNMw7DuF+rPCdPYzedP1aVtI7SNR26M2/uE7cMqGkKfuaUhHZk237N05DJ+5HAZYneeXldmKUiP7yBGpmvgL0F5d/q89nZXiwIqN/V4HU5cgv+ZOr6BTKXhrVoOOApFHbiLWiCX153aP077g6B7dFYNWh3I0bvhfUmA/HMVkuv33hSSI66kMoBfVLNkqjvdYNT8jTYA1dDW6N+5ODxzEKwAInXQfOHX2nKFoROB6OENJz6ud6gM98FmFk1VcmkjtXT5ypmswCUa+a5n0hoMmkdjdmMMvtyZHIYCk5bLusLfPpoH2bQIDAQAB",
                "UTF-8",
                "RSA2"); //调用SDK验证签名

        if (signVerfied) {

            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            if(paramsMap.get("out_trade_no").equals("20200313105750004")&&
                    paramsMap.get("total_amount").equals("2000000.88")){
                System.out.println("金额正确，验签成功");//要去数据库中改变订单状态
                //TODO response.getWriter().write("json");

            }

        } else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            System.out.println("验签失败");
        }


    }

}


//




//    @RequestMapping("alipay")
//    public void doPay(HttpServletRequest httpRequest,
//                      HttpServletResponse httpResponse,String oid) throws ServletException, IOException {
//        /**
//         *参数说明：
//         * 1. 支付网关
//         * 2.应用id
//         * 3.商户应用私钥
//         * 4.返回的数据类型： json
//         * 5.字符集： utf-8
//         * 6. 支付宝公钥  注意，是支付宝公钥，不是商户公钥
//         * 7. 密钥生成方式： RSA2
//         */
//        AlipayClient alipayClient =
//                new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
//                        "2016101900725231",
//                        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLCXuZFtjDvVtL7oX/Xe4hQh8InMVkZ6yAoxd/h3e7YNnSmcRTbp0xn0Ol3JHHaCGX7qkM4tKTBvG23S7P2PDtzu/4y4CFDG7sei3y6CUZSjsrdM+HpDBo46IyFDVaOQNcUT9NFCtJtEsrO+ZDbAcrq6pFH+8ynY9K+WpQb7wYwPL1bKZxa5Z9QGOJ63iQKRvKOFRNJJxET6z5UGlEc2+uUHsW6kgXJ6WPm9nPHeGiowRWnbwc+cC/4QBDe1NiKcrqDucbk4tRlMszFdc3yGrbB/BWNT+fjSgqthMWdkTP5b+XnZntBE4MQC8V9mdENaqZb/E9h2dEXniQFIVAXiRHAgMBAAECggEAW5BrLW62YnIZ5e+3n22knZKGDY3xESaVnEHL/9ifKW+nA+LwQGHgdAWG73xLJR+WwBAUlL/sHZe9J8iSQ5+DS5m0wAyFHxoJEwODryzjAby5Ku1KnvGqT+lZr9FPMZPKesmm/oQB3hA2UMqp4k0Ki+AJymw1gwfwjlejhEWRglrWEOVJlkpUckEmjXcH7PNiIkoBzSMfc8RuoeIKLMzVpoWx0vi16oMeXQPZim7eWHYZlqyGOTKKfd6yaweHa401iQqB9+pzLZbekmkVQPriG71+he0c7CRaUurTAzmqbsYH5Bbbg8RfC2KbEhlW+1/BGqvC41/aCaMx/tGrIECrgQKBgQDPLbatLvn0LsugNTZ8+pXRZOCQtPQ1RUFaH8PwZW0WUgk3iRSmpALx4aJOim+GcLyukxqIJvEs0hV1NBZXGXA3FUiULS4RTnEfDUwi8makeVxZWscJ5/ZvKmiwcxmQJp4faH4zlYwj62KA3vOKOXNZtnh0d8yUUrimcafybPb+XwKBgQCrzQ2N2x57p2To015ybSCPBjnMSH0y5rziBT9W80rasWLg5hQ2tmxZJEICws3oIR+AcQ2jDuS67nPN0F4XK7RmGTMEYof0lC+bApTAHyKldV1silUXV0FFmpVhmxPt4o0B69gVLy8SpDOTnT4fruaW9TTnZpLWfnPJF1UGsMnTGQKBgG/CcC3CDpH7gFq++dK3doQLT9yf0LC/2D4erpsKi6sju9caempeRTxoBB8sLHcwb4gY0JIrt6P+/BZKb9ayYUdFku5j5NrvHrSqfqzHaDlHQlrtTjt4xwY2sVyl6l9JhbjZrGJ1RLDHtE5idqvUy/XUKexiB5jnerZGz1tGDoMvAoGBAKoHZdu4OgINWHxo/Ldos2l5sugv8eDXpaZXpSlL3hB0sLR+YREJGFBc5wvOenS7m27F9MYlLlCnQGs4RnbOJVtKo0g6r+1qX3cdZdSCvApfDpgmjDJug8X8SM1x6pZrujxlitTkfsUHR5hXbi1zLvnGMpa12Kt6OOOTOO5HN2e5AoGAZYqQiRCpy5u8B8xYhrawFIqeVKpGmKKIaz/9QXyuWcJl5K1IhMef8wQVZtPLxUKAZmLHqtjHJaJsl4/aBU8z8xLhQe/7Vaw0nWWP7H7faCcmZDSi3s5CM6hkMAl3khuoQhTOgTrw9NpWgatsA+AlxCvlaRjgzuLSLPm/ZkZzJyM=",
//                        "json",
//                        "UTF-8",
//                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiwl7mRbYw71bS+6F/13uIUIfCJzFZGesgKMXf4d3u2DZ0pnEU26dMZ9DpdyRx2ghl+6pDOLSkwbxtt0uz9jw7c7v+MuAhQxu7Hot8uglGUo7K3TPh6QwaOOiMhQ1WjkDXFE/TRQrSbRLKzvmQ2wHK6uqRR/vMp2PSvlqUG+8GMDy9WymcWuWfUBjiet4kCkbyjhUTSScRE+s+VBpRHNvrlB7FupIFyelj5vZzx3hoqMEVp28HPnAv+EAQ3tTYinK6g7nG5OLUZTLMxXXN8hq2wfwVjU/n40oKrYTFnZEz+W/l52Z7QRODEAvFfZnRDWqmW/xPYdnRF54kBSFQF4kRwIDAQAB",
//                        "RSA2"); //获得初始化的AlipayClient
//
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
//        alipayRequest.setReturnUrl(natAppIp+"/success");
//        alipayRequest.setNotifyUrl(natAppIp+"/notifyUrl");//在公共参数中设置回跳和通知地址
//        alipayRequest.setBizContent("{" +
//                "    \"out_trade_no\":\""+oid+"\"," +
//                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
//                "    \"total_amount\":88.88," +
//                "    \"subject\":\"Iphone16 16G\"," +
//                "    \"body\":\"Iphone16 16G\"," +
//                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
//                "    \"extend_params\":{" +
//                "    \"sys_service_provider_id\":\"2088511833207846\"" +
//                "    }"+
//                "  }");//填充业务参数
//        String form="";
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        httpResponse.setContentType("text/html;charset=utf-8");
//        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
//    }

//
//    @RequestMapping("notifyUrl")
//    @ResponseBody
//    public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws AlipayApiException, IOException {
//
//        Map<String, String[]> map = request.getParameterMap();
//        //需要将map中的String[]==>String
//        Map<String, String> paramsMap = new HashMap<>(); //将异步通知中收到的所有参数都存放到 map 中
//
//        Set<Map.Entry<String, String[]>> entries = map.entrySet();
//        for (Map.Entry<String, String[]> entry : entries) {
//            String[] values = entry.getValue();
//            StringBuffer sb = new StringBuffer();
//            for (int i = 0; i < values.length-1; i++) {
//                sb.append(values[i]+",");
//            }
//            sb.append(values[values.length-1]);
//            paramsMap.put(entry.getKey(),sb.toString());
//        }
//
//
//        boolean signVerfied = AlipaySignature.rsaCheckV1(paramsMap,
//                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgO/rQgSZvR/afCbY6qADRmx1VS5B9f1h41F6dNMw7DuF+rPCdPYzedP1aVtI7SNR26M2/uE7cMqGkKfuaUhHZk237N05DJ+5HAZYneeXldmKUiP7yBGpmvgL0F5d/q89nZXiwIqN/V4HU5cgv+ZOr6BTKXhrVoOOApFHbiLWiCX153aP077g6B7dFYNWh3I0bvhfUmA/HMVkuv33hSSI66kMoBfVLNkqjvdYNT8jTYA1dDW6N+5ODxzEKwAInXQfOHX2nKFoROB6OENJz6ud6gM98FmFk1VcmkjtXT5ypmswCUa+a5n0hoMmkdjdmMMvtyZHIYCk5bLusLfPpoH2bQIDAQAB",
//                "UTF-8",
//                "RSA2"); //调用SDK验证签名
//
//
//        if(signVerfied){
//            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
//            if(paramsMap.get("out_trade_no").equals("20200313105750004")&&
//                    paramsMap.get("total_amount").equals("2000000.88")){
//                System.out.println("金额正确，验签成功");//要去数据库中改变订单状态
//                //TODO response.getWriter().write("json");
//
//            }
//        }else{
//            // TODO 验签失败则记录异常日志，并在response中返回failure.
//        }
//
//
//    }
